package work;

public class Work2 {
    int j = 0;
    int i = 0;
}

class W2add implements Runnable{
    private Work2 w;

    public W2add(Work2 w) {
        this.w = w;
    }

    @Override
    public void run() {
        while (true){
            synchronized (w) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                add();
            }
        }
    }

    public void add(){
        w.j++;
        w.i++;
        System.out.println(Thread.currentThread().getName() + "i=" + w.i + "j=" + w.j);
    }
}

class W2cut implements Runnable{
    private Work2 w;

    public W2cut(Work2 w) {
        this.w = w;
    }

    @Override
    public void run() {
        while (true){
            synchronized (w) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                cut();
            }
        }
    }

    public void cut(){
        w.j--;
        w.i--;
        System.out.println(Thread.currentThread().getName() + "i=" + w.i + "j=" + w.j);
    }
}

class TestWork2{
    public static void main(String[] args) {
        Work2 w2 = new Work2();
        for (int i = 1; i <= 2; i++) {
            new Thread(new W2add(w2),"第" + i + "个加法").start();
            new Thread(new W2cut(w2),"第" + i + "个减法").start();
        }
    }
}